//
//  CreateGroupViewController.m
//  EnjoyAll
//
//  Created by 王晓冰 on 2017/11/2.
//  Copyright © 2017年 张雷. All rights reserved.
//

#import "CreateGroupViewController.h"
#import "UpImageCell.h"
#import "SelectMemberViewController.h"
#import "MembersViewController.h"
#import "GroupSetTableViewCell.h"
#import "TextFieldCell.h"
#import "TextViewCell.h"
#import "CompanyViewController.h"

@interface CreateGroupViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)UITextField *groupL;@property (nonatomic,strong)NSMutableDictionary *paramDict;
@property (nonatomic,copy)NSString *groupDetail;

@end

@implementation CreateGroupViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"发起群聊";
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, kSCREEN_HEIGHT-64-72) style:UITableViewStylePlain];
    tableView.backgroundColor = [UIColor colorWithHexString:@"ebebeb"];
    self.tableView = tableView;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tableFooterView = [[UIView alloc] init];
     self.tableView.tableHeaderView = [self headerView];
    [self.view addSubview:tableView];
    [self initBottmView];
    [self _setupBarButtonItem];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //刷新单元格（pop回来后，刷新单元格改变数据）
    [self.tableView reloadData];
    
}

- (UIView *)headerView
{
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, 115+8+56)];
    headerView.backgroundColor = KWhiteColor;
    
    UIButton *userIcon = [[UIButton alloc]initWithFrame:CGRectMake((kSCREEN_WIDTH-75)*0.5, 20, 75, 75)];
    ViewRadius(userIcon ,75*0.5);
    [userIcon setTitle:@"群" forState:UIControlStateNormal];
    userIcon.font = [UIFont boldSystemFontOfSize:28];
    userIcon.backgroundColor = [UIColor colorWithHexString:@"2c9ae8"];
    [userIcon setTitleColor:KWhiteColor forState:UIControlStateNormal];
    
    [headerView addSubview:userIcon];
    
    UIView *nillView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(userIcon.frame)+20, kSCREEN_WIDTH, 8)];
    nillView.backgroundColor = [UIColor colorWithHexString:@"ebebeb"];
    [headerView addSubview:nillView];
    
    UIView *View = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(nillView.frame), kSCREEN_WIDTH, 56)];
    View.backgroundColor = KWhiteColor;
    [headerView addSubview:View];
    
    
    UILabel *namelable = [UILabel labelWithFrame:CGRectMake(15,18 , 100, 20) Font:FONT(15) TextColor:[UIColor colorWithHexString:@"454545"]];
    namelable.text = @"群名称";
    [View addSubview:namelable];
    
    UITextField *groupL = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(namelable.frame)+18, 18, kSCREEN_WIDTH-(CGRectGetMaxX(namelable.frame)+28), 20)];
    
    groupL.font = FONT(14);
    groupL.textColor = [UIColor colorWithHexString:@"999999"];
    groupL.placeholder = @"请输入群名称";
    self.groupL = groupL;
    [View addSubview:groupL];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(headerView.frame)-1, kSCREEN_WIDTH, 1)];
    lineView.backgroundColor = KLineColor;
    [headerView addSubview:lineView];
    
    return headerView;
    
}


- (void)initBottmView{
    
    UIView *footView= [[UIView alloc]initWithFrame:CGRectMake(0,kSCREEN_HEIGHT-72-64, kSCREEN_WIDTH, 72)];
    [self.view addSubview:footView];
    
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(15, 10, kSCREEN_WIDTH-30, 52)];
    btn.layer.cornerRadius = 52*0.5;
    btn.layer.masksToBounds = YES;
    btn.backgroundColor = [UIColor colorWithHexString:@"2c9ae8"];
    btn.titleLabel.font = [UIFont systemFontOfSize:18];
    [btn setTitle:@"确认创建" forState:UIControlStateNormal];
    [btn setTitleColor:KWhiteColor forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(creatGroup) forControlEvents:UIControlEventTouchUpInside];
    [footView addSubview:btn];
    
}

- (void)creatGroup{
    if ([_groupL.text isEqualToString:@""] ) {
        [self showAlert:@"请输入群名称"];
        return;
    }
    
    NSMutableArray *logiNameArr = [NSMutableArray array];
    for (SelectModel *model in self.allModels) {
        [logiNameArr addObject:model.loginName];
    }
    
    NSMutableDictionary * paramDict = [[NSMutableDictionary alloc] init];

//    [paramDict setValue:[DataCenter shareInstence].companyId forKey:@"companyId"];
    [paramDict setValue:self.companyId forKey:@"companyId"];
//    [paramDict setValue:@"" forKey:@"desc"];
    [paramDict setValue:@1 forKey:@"groupType"];

    [paramDict setValue:self.groupL.text forKey:@"groupname"];

    [paramDict setValue:logiNameArr forKey:@"members"];

    [paramDict setValue:[DataCenter shareInstence].loginName forKey:@"owner"];
//    [paramDict setValue:@1 forKey:@"publicFlag"];
    NSLog(@"%@",paramDict);
    
    [ZLHXHelper postURL:@"im/createGroup" paramDict:paramDict completion:^(NSDictionary *responseObject) {
      
        iToast *itost = [[iToast alloc] initWithText:@"创建成功"];
        [itost show];
        [self.navigationController popToRootViewControllerAnimated:YES];
    } error:^(NSError *error) {
        
       
        
    }];
    
    
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return 5;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 125;
    }
    if (indexPath.row == 1) {
        CGSize size = [Tool boundingRectWithSize:self.groupDetail Font:[UIFont systemFontOfSize:16] Size:CGSizeMake(kSCREEN_WIDTH-150, MAXFLOAT)];
        
        return size.height>20?(size.height+8):44;
    }
    
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row
        == 0) {
        
        UpImageCell *membersCell = [UpImageCell cellWithTableView:tableView];
        
        membersCell.countL.text = [NSString stringWithFormat:@"%ld",self.allModels.count];
        
        
        //对collectionView的展示切割名字
        NSMutableArray *arr = [[NSMutableArray alloc] init];
        for (SelectModel* model in self.allModels) {
            NSString *n;
            if (model.name.length>2) {
                n = [model.name substringFromIndex:1];
            }else{
                n = model.name;
            }
            [arr addObject:n];
        }
        
        
        if (arr.count <= 4) {
            [arr addObject:@"+"];
            [arr addObject:@"-"];
        }else{
            
            arr = [[arr subarrayWithRange:NSMakeRange(0, 4)] mutableCopy];
            [arr addObject:@"+"];
            [arr addObject:@"-"];
            
        }
        membersCell.nameArray = arr;
        
        membersCell.block = ^(NSInteger collctionItem){
            
            if (collctionItem == arr.count-2) {
                //添加人
                NSLog(@"添加人");
                if (self.block) {
                    self.block(self.allModels);
                }
                [self.navigationController popViewControllerAnimated:YES];
                
//                for (UIViewController *temp in self.navigationController.viewControllers) {
//                    if ([temp isKindOfClass:[CompanyViewController class]]) {
//                    CompanyViewController *vc = (CompanyViewController *)temp;
//
//                    }
//
//
//                }
                
            }else if (collctionItem == arr.count-1){//减人
                
                MembersViewController *memberVC = [[MembersViewController alloc] init];
                memberVC.block = ^(NSMutableArray *modalsArr) {
                    self.allModels = [modalsArr mutableCopy];
                    [self.tableView reloadData];
                };
                memberVC.modalsArr = [self.allModels mutableCopy];
                
                [self.navigationController pushViewController:memberVC animated:YES];
            }
            
        };
        
        return membersCell;
        
    }
    
    if (indexPath.row == 3 || indexPath.row == 4){
        GroupSetTableViewCell *groupCell = [GroupSetTableViewCell cellWithTableView:tableView];
        if (indexPath.row == 3) {
            groupCell.titleName.text = @"入群是否需要批准";
            groupCell.block = ^(BOOL isOn) {
                [self.paramDict setValue:@0 forKey:@"approval"];
            };
        }else if (indexPath.row == 4) {
            groupCell.titleName.text = @"是否为公开群";
            groupCell.block = ^(BOOL isOn) {
                [self.paramDict setValue:@1 forKey:@"publicFlag"];
            };
        }
        return groupCell;
    }
    if (indexPath.row == 1) {
        TextViewCell *textViewCell = [TextViewCell cellWithTableView:tableView];
        textViewCell.changeTextBlock = ^(UITextView *textView) {
            self.groupDetail = textView.text;
            [self.paramDict setValue:textView.text forKey:@"desc"];
            [self.tableView beginUpdates];
            [self.tableView endUpdates];
        };
        return textViewCell;
    }
    
    TextFieldCell *textCell = [TextFieldCell cellWithTableView:tableView];
    textCell.textFieldBlock = ^(UITextField *textField) {
        [self.paramDict setValue:textField.text forKey:@"maxusers"];
    };
    return textCell;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //查看全部成员
    if (indexPath.row == 0) {
        MembersViewController *memberVC = [[MembersViewController alloc] init];
        memberVC.notAdmin = YES;
        memberVC.modalsArr = self.allModels;
        [self.navigationController pushViewController:memberVC animated:YES];
    }
    
}


- (void)_setupBarButtonItem
{
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    backButton.frame = CGRectMake(0, 0, 44, 44);
    
    [backButton setImage:[UIImage imageNamed:@"ev_nav_back"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
}

- (void)backAction{
    
    [self.navigationController popToRootViewControllerAnimated:YES];
    
}
- (NSMutableDictionary *)paramDict{
    if (!_paramDict) {
        _paramDict = [NSMutableDictionary dictionary];
    }
    return _paramDict;
}

@end
